behind
the  
codes
{

Programming, web design, gadgets, and anything beyond

innerText/jQuery demo

Given an HTML element, and considering that element might contain subelement(s), how do you get only the textual data of that element? Easy peasy… use innerText of course. WRONG! In case you don’t know, innerText only works on IE!!!.

That’s one example of how cross-browser incompatibility destroy our coding happiness, and sometimes take our sense of pride and accomplishment with it. We need to spend more time researching how this works on other browsers, as well as more time implementing the solution that will work on all browsers we support. Well sure some of you might know how to do innerText on FF and Chrome, but wouldn’t it be nice if all browsers work the same way?

jQuery to the rescue! To get the text, just use text property. That’s it, and it will run on all IE, FF, Chrome, etc. Don’t believe me? Run this in Internet Exporer, Firefox, Chrome, etc, and compare the result.

For more information about jQuery (and to read the source article for this demo), click here: Use the jQuery, Luke!

Execution
Source
This is the content of a div.

The content of the div above will be copied down here…

…without using jquery: ???
…using jquery: ???

<html>
<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
	<script type="text/javascript">
		window.onload = function() {
			document.getElementById("dst_no_jquery").innerText = document.getElementById("source").innerText;
		}
		$(document).ready(function() {
			$("#dst_with_jquery").text($("#source").text());
		});
	</script>
</head>
<body>
	<div id="source" style="border: 1px dashed #ccc">This is <b>the <i>content</i></b> of a div.</div>
	<p>The content of the div above will be copied down here...
		<div>...without using jquery: <u id="dst_no_jquery">???</u></div>
		<div>...using jquery: <u id="dst_with_jquery">???</u></div>
	</p>
</body>
</html>


Share and Enjoy:
  • Print
  • email
  • RSS
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Twitter
  • Google Bookmarks
  • Add to favorites
  • Reddit
  • Digg
  • Slashdot

Leave a Reply